#!/usr/bin/env python2

import subprocess, time, os, sys, random

def instanceFromFile(path):
	f = open(path)
	input = ""
	for line in f:
		input += line
	return input.strip()

def toDot(path):
	f = open(path)
	input = []
	for line in f:
		input.append(line.strip())
		
	input = input[1:]
	
	dotFile = ""
	dotFile += "Graph G {\n"
	
	for line in input:
		dotFile += line.replace(" ", " -- ", 1) + ";\n"
	
	dotFile += "}\n"
	
	subp = subprocess.Popen(["dot", "-Tpng", "-o"+path+".png"], stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
	stdout = subp.communicate(input=dotFile)[0]


def launch(cmd, input):
	command = [cmd]
	subp = subprocess.Popen(command, stdout=subprocess.PIPE, stdin=subprocess.PIPE, stderr=subprocess.STDOUT)
	stdout = subp.communicate(input=input)[0]
	return stdout.strip()


folder = "tests/"
n = 2
count = 100

output1 = ""
output2 = ""
output3 = ""
output4 = ""
res = open("resultados.txt", "w+")

while n < 100:

	m = ((n-1)*(n-2)/2) +1

	matriz = []
	for i in range(n):
		matriz.append([])
		for j in range(n):
			matriz[i].append(0)
	i = 0
	while i < m:
		x = random.randint(0,n-1)
		y = random.randint(0,n-1)
		if((y == x) or (matriz[x][y] == 1)):
			continue
			
		matriz[x][y] = 1
		matriz[y][x] = 1
		i = i+1

	filename = folder + "test-" + str(n) + ".txt"
	fle = open(filename, "w+")	
	print "Generating test: " + filename + "..."
	fle.write(str(n) + " " + str(m) + "\n")

	for i in range (n):
		for j in range(i,n):
			if matriz[i][j] == 1:
				fle.write(str(i+1) + " " + str(j+1) + "\n")

	fle.close()
	
	toDot(filename)
	
	output1 = launch("./exacto", instanceFromFile(filename))
	output2 = launch("./goloso", instanceFromFile(filename))
	output3 = launch("./local", instanceFromFile(filename))
	output4 = launch("./tabu", instanceFromFile(filename))
	res.write(filename + " -- Exacto: " + output1 + "\n")
	res.write(filename + " -- Goloso: " + output2 + "\n")
	res.write(filename + " -- Local:  " + output3 + "\n")
	res.write(filename + " -- Tabu:   " + output4 + "\n")
	res.write("------------------------------------------------------------------\n")
	
	n = n+1

res.close()
